package com.le.tester.imooc.masterJUC.lock.reentrantlock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 描述：
 */
public class CinemaReadWrite {

    //多读，要控制成唯一写
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(false);
    //读
    private static ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    //写
    private static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    public static void main(String[] args) {
        //在非公平策略中
        //不允许读锁和写锁同时进行，那么源码中会在队列中查看正在操作的是读还是写
        //前一个是读锁，下一个还是读锁，允许读，下一个是写锁，等待读锁执行完毕，再进行写锁
        //但是如果前一个是写锁，后一个也是写锁，还是可以进行操作，并不会阻塞。
        new Thread(CinemaReadWrite::write, "Thread1").start();
        new Thread(CinemaReadWrite::read, "Thread2").start();
        new Thread(CinemaReadWrite::read, "Thread3").start();
        new Thread(CinemaReadWrite::write, "Thread4").start();
        new Thread(CinemaReadWrite::write, "Thread5").start();
        new Thread(CinemaReadWrite::read, "Thread6").start();

    }


    private static void read() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 得到了读锁，正在读取中");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + " 释放了读锁");
            readLock.unlock();
        }
    }

    private static void write() {
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 得到了写锁，正在写入中");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + " 释放了写锁");
            writeLock.unlock();
        }
    }
}
